#!/usr/bin/env python2

import os
import sys
import socket
import time
import subprocess
import fcntl
import types
import errno
import getopt
import random
import threading
import traceback
import json
import urllib2

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
#import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

#sys.path.insert(0, os.path.split(os.path.realpath(__file__))[0] + "/../")

from daemon import Daemon
from config import Config
from utils import _dmsg

config = Config()


class Handler(BaseHTTPRequestHandler):
    def __sendfile(self, path):
        size = os.path.getsize(path)
        _dmsg("%s size %u" % (path, size))

        fd = open(path, 'r')
        left = size
        while (left > 0):
            if (left > 524288):
                cp = 524288
            else:
                cp = left

            #_dmsg("send %s %u"  % (path, cp))
            buf = fd.read(cp)
            self.wfile.write(buf)
            left -= cp

        fd.close()

        return

    def __get_io(self):
        tmp = config.home + '/tmp/dump'
        name ='io.' + str(int(time.time()))
        tar = tmp +'/' +  name + '.' + 'tar.gz'
        os.system('mkdir -p %s/dump/io' % (tmp))
        cmd = 'mv %s/io %s/%s > /dev/null 2>&1' % (tmp, tmp, name)
        #_dmsg(cmd)
        os.system(cmd)
        cmd = 'tar czvf %s -C %s %s >> /dev/null && rm -rf %s' % (tar, tmp, name, tmp + '/' + name)
        #_dmsg(cmd)
        os.system(cmd)

        self.send_response(200)
        size = os.path.getsize(tar)
        self.send_header('Content-type', 'application/gzip')
        self.send_header('Content-length', str(size))
        self.end_headers()

        self.__sendfile(tar)

        cmd = 'rm %s' % (tar)
        #_dmsg(cmd)
        os.system(cmd)
        return

    def do_GET(self):
        if (self.path == '/io.tar.gz'):
            self.__get_io()
        else:
            self.send_response(404)
            self.end_headers()

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

class Lich_Dump(Daemon):
    def __init__(self):
        self.config = Config()
        os.system('mkdir -p ' + self.config.home + '/tmp')
        os.system('mkdir -p ' + self.config.home + '/log')
        pidfile = '/var/run/lich_dump.pid'
        log = self.config.home + '/log/lich_dump.log'
        os.system('touch ' + log)
        super(Lich_Dump, self).__init__(pidfile, '/dev/null', log, log, 'lich_dump')

    def run(self):
        #sys.stdout.write('out:run\n')
        #sys.stderr.write('err:run\n')
        server = ThreadedHTTPServer(('', 27902), Handler)
        server.serve_forever()

def usage():
    print ("usage:")
    print (sys.argv[0] + " --start")
    print (sys.argv[0] + " --stop")
    print (sys.argv[0] + " --test")
    print (sys.argv[0])

def main():
    op = ''
    ext = None
    try:
        opts, args = getopt.getopt(
                sys.argv[1:], 
            'h', ['start', 'stop', 'help', 'test']
                )
    except getopt.GetoptError, err:
        print str(err)
        usage()

    lich_dump = Lich_Dump()
    for o, a in opts:
        if o in ('--help'):
            usage()
            exit(0)
        elif (o == '--start'):
            op = o
            lich_dump.start()
        elif (o == '--stop'):
            op = o
            lich_dump.stop()
        elif (o == '--test'):
            lich_dump.run()
        else:
            assert False, 'oops, unhandled option: %s, -h for help' % o
            exit(1)

if __name__ == '__main__':
    if (len(sys.argv) == 1):
        usage()
    else:
        main()
